<?php

class ArticleHolder extends Page{
    private static $db = array();
    private static $has_one = array(
        'ArticleCategory' => 'ArticleCategory'
    );
    static $allowed_children = array("ArticleHolder");

    public function getCMSFields(){
        $fields = parent::getCMSFields();
        $fields->removeByName('Content');

        $arrCategory = ArticleCategory::get()->map('ID', 'Title')->toArray();
        asort($arrCategory);
        $categoryField = new DropdownField('ArticleCategoryID', 'Category', $arrCategory);
        $categoryField->setEmptyString('Select one');

        $fields->addFieldToTab('Root.Main', $categoryField, 'Metadata');

        $articleConfig = GridFieldConfig_RecordEditor::create()->addComponent(new GridFieldSortableRows('SortOrder'));
        $articleConfig->removeComponentsByType('GridFieldAddNewButton');
        $articleConfig->removeComponentsByType('GridFieldDeleteAction');
//        $articleConfig->removeComponentsByType('GridFieldEditButton');

        $articleGridField = new GridField(
            'Article',
            'Article',
            Article::get()->leftJoin('Article_ArticleCategories', "Article.ID = Article_ArticleCategories.ArticleID")->filter(array('ArticleCategoryID' => $this->ArticleCategory()->ID)),
            $articleConfig
        );
        $fields->findOrMakeTab('Root.ArticlesTab', 'Article');
        $fields->addFieldToTab('Root.ArticlesTab', $articleGridField);


        return $fields;
    }

    function getCurrentArticleTitle(){
        return Session::get('ArticleDetailTitle');
    }

}

class ArticleHolder_Controller extends Page_Controller{
    static $allowed_actions = array(
        'ns'
    );

    public function ns(){
        $paramID = $this->request->param('ID');
        $articleUrlSegment = SiteTree::create()->generateURLSegment($paramID);
        $article = Article::get()->filter(array('UrlSegment' => $articleUrlSegment))->first();
        if($article){
            Session::set('ArticleDetailTitle', $article->Title);
            return $this->customise(array('Article' => $article))->renderWith(array('ArticleDetailPage', 'Page'));
        }
        return $this->redirectBack();
    }

    public function PaginatedArticleByCategory() {
        $paginatedList = new PaginatedList($this->ArticleCategory()->Articles(), $this->request);
        $paginatedList->setPageLength(12);
        return $paginatedList;
    }

    function getCurrentArticle(){
        $paramID = $this->request->param('ID');
        $articleUrlSegment = SiteTree::create()->generateURLSegment($paramID);

        return Article::get()->filter(array('UrlSegment' => $articleUrlSegment))->first();
    }

}